package com.chenfan.mcn.exception;

import com.chenfan.common.exception.BusinessException;
import com.chenfan.common.exception.GlobalDefaultExceptionHandler;
import com.chenfan.common.vo.Response;
import feign.FeignException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.concurrent.CompletionException;

/** 默认全局异常处理-增强
 * @author wulg
 * @date 2021-10-28
 **/
@RestControllerAdvice
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class EnhancedGlobalExceptionHandler extends GlobalDefaultExceptionHandler {

    @ExceptionHandler({FeignException.class})
    public Response handlerFeignException(Exception e) {
        if(e.getCause() != null && e.getCause() instanceof RpcResultException ) {
            RpcResultException ex = (RpcResultException)e.getCause();
            int code = ex.getState().code();
            String message = ex.getState().message();
            //客户数据转移失败-目标用户负责客户数量超出限制
            if(code == RpcResultErrorCode.TARGET_CUSTMOER_EXCEED_LIMIT.code()) {
                return this.handlerBusinessException(ex);
            } else {
                String errorMessage = String.format("%s --> %s %s <-- 操作失败【%s-%s】", ex.getServiceId(), ex.getHttpMethodName(), ex.getUri(),
                        code, message);
                return Response.error(McnErrorCode.CLIENT_RESPONSE_FAILED.code(), errorMessage);
            }
        }
        return Response.error(McnErrorCode.ERROR.code(), StringUtils.defaultString(e.getMessage(), McnErrorCode.ERROR.message()));
    }

    @ExceptionHandler({CompletionException.class})
    public Response handlerCompletionException(Exception e) {
        Throwable throwable = e.getCause();
        if(throwable instanceof FeignException) {
            FeignException feignException = (FeignException)throwable;
            return this.handlerFeignException(feignException);
        } else if(throwable instanceof BusinessException) {
            return Response.error(((BusinessException)throwable).getState());
        }
        return Response.error(McnErrorCode.ERROR.code(), StringUtils.defaultString(throwable.getMessage(), McnErrorCode.ERROR.message()));
    }

    @ExceptionHandler({RepeatedDataExeception.class})
    public Response handlerCompletionException(RepeatedDataExeception e) {
        Response<Object> response = Response.error(e.getState());
        response.setObj(e.getData());
        return response;
    }
}
